package com.zjj.lbw.spring.security.controller;

import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;

@RestController
@RequestMapping("/admin")
class AdminController {
    @RequestMapping("/demo")
//    @PermitAll
//    @RolesAllowed("admin")
//    @Secured("ROLE_admin") // 这种方式只能基于角色控制，而且必须以ROLE_开头
    @PreAuthorize("hasAnyAuthority('ROLE_admin')")
    public String demo() {
        return "spring security demo";
    }

    @GetMapping("/index")
    @PreAuthorize("#id<10")
    public String index(int id) {
        String username = getUsername();
        return username + "登录成功";
    }

    private String getUsername() {
        // 获取当前登录的用户信息
        Authentication authentication =
                SecurityContextHolder.getContext().getAuthentication();
        if (!authentication.isAuthenticated()) {
            return null;
        }
        Object principal = authentication.getPrincipal();
        String username = null;
        if (principal instanceof UserDetails) {
            username = ((UserDetails) principal).getUsername();
        } else {
            username = principal.toString();
        }
        return username;
    }
}
